package com.zbar.woke;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.widget.Toast;

import com.example.woke.ChannelActivateActivity;
import com.example.woke.ZhongcaiReciveActivity;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.http.HttpMethods;
import com.nova.lfh.zxing.RScannerActivity;
import com.woke.method.MyApp;
import com.woke.serizedatas.Datas_load;
import com.zhongcai.online.R;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 作�?: 陈涛(1076559197@qq.com)
 * <p>
 * 时间: 2014�?�?�?下午12:25:31
 * <p>
 * 版本: V_1.0.0
 * <p>
 * 描述: 扫描界面
 */
public class CaptureActivity extends Activity implements EasyPermissions.PermissionCallbacks {
	private static final int CAMERA = 88;

//	private CaptureActivityHandler handler;
//	private boolean hasSurface;
//	private InactivityTimer inactivityTimer;
//	private MediaPlayer mediaPlayer;
//	private boolean playBeep;
//	private static final float BEEP_VOLUME = 0.50f;
//	private boolean vibrate;
//	private int x = 0;
//	private int y = 0;
//	private int cropWidth = 0;
//	private int cropHeight = 0;
//	private RelativeLayout mContainer = null;
//	private RelativeLayout mCropLayout = null;
//
//	public int getX() {
//		return x;
//	}
//
//	public void setX(int x) {
//		this.x = x;
//	}
//
//	public int getY() {
//		return y;
//	}
//
//	public void setY(int y) {
//		this.y = y;
//	}
//
//	public int getCropWidth() {
//		return cropWidth;
//	}
//
//	public void setCropWidth(int cropWidth) {
//		this.cropWidth = cropWidth;
//	}
//
//	public int getCropHeight() {
//		return cropHeight;
//	}
//
//	public void setCropHeight(int cropHeight) {
//		this.cropHeight = cropHeight;
//	}

	/**
	 * Called when the activity is first created.
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate (savedInstanceState);

		setContentView (R.layout.activity_qr_scan);

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
			methodRequiresTwoPermission ();
		} else {
			new IntentIntegrator (this).setCaptureActivity (RScannerActivity.class).initiateScan ();
		}
	}

	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
		super.onRequestPermissionsResult (requestCode, permissions, grantResults);
		EasyPermissions.onRequestPermissionsResult (requestCode, permissions, grantResults, this);
	}

	@AfterPermissionGranted(CAMERA)
	private void methodRequiresTwoPermission() {
		String[] perms = {Manifest.permission.CAMERA};
		if (EasyPermissions.hasPermissions (this, perms)) {
			new IntentIntegrator (this).setCaptureActivity (RScannerActivity.class).initiateScan ();
		} else {
			// Do not have permissions, request them now
			EasyPermissions.requestPermissions (this, "需要读取本地文件权限",
					CAMERA, perms);
		}
	}

	@Override
	public void onPermissionsGranted(int requestCode, List<String> perms) {
		if (requestCode == CAMERA) {
			new IntentIntegrator (this).setCaptureActivity (RScannerActivity.class).initiateScan ();
		}
	}

	@Override
	public void onPermissionsDenied(int requestCode, List<String> perms) {
		if (requestCode == CAMERA) {
			new AlertDialog.Builder (this).setMessage ("请在<权限管理>里打开相机权限")
					.setPositiveButton ("前往", new DialogInterface.OnClickListener () {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							Intent intent = new Intent (Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
							intent.setData (Uri.fromParts ("package", getPackageName (), null));
							startActivity (intent);
							dialog.dismiss ();
						}
					})
					.setNegativeButton ("取消", new DialogInterface.OnClickListener () {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							finish ();
						}
					})
					.create ()
					.show ();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		IntentResult result = IntentIntegrator.parseActivityResult (requestCode, resultCode, data);
		if (result != null) {
			if (TextUtils.isEmpty (result.getContents ())) {

			} else {
				String serialNum = getserialNumberFromUrl (result.getContents ());
				if (! TextUtils.isEmpty (serialNum)) {
					//商家激活码
					Datas_load datasLoad = MyApp.getInstance ().getDatas_load ();
					if (datasLoad == null) {
						Toast.makeText (this, "您还未登录", Toast.LENGTH_SHORT).show ();
					} else {
						HttpMethods.getInstance ()
								.activateSeriesNo (mActivateObserver, Integer.parseInt (datasLoad.getId ()), serialNum);
					}
				} else {
					Intent intent = new Intent (CaptureActivity.this, ZhongcaiReciveActivity.class);
					intent.putExtra ("result", result.getContents ());
					startActivity (intent);
					Toast.makeText (getApplicationContext (), result.getContents (), Toast.LENGTH_SHORT)
							.show ();
				}
			}
		} else {
			// This is important, otherwise the result will not be passed to the fragment
			super.onActivityResult (requestCode, resultCode, data);
		}

		finish ();
	}

	/**
	 * 截取链接上的 的serialNumber值
	 * &serialNumber=42b26142ca6f180d
	 *
	 * @param urlStr
	 * @return
	 */
	private String getserialNumberFromUrl(String urlStr) {
		Pattern p = Pattern.compile ("&serialNumber=[A-Za-z0-9]+");
		Matcher m = p.matcher (urlStr);
		if (m.find ()) {
			String[] split = m.group ().split ("=");
			return split[1];
		}
		return "";
	}


	private Observer<String> mActivateObserver = new Observer<String> () {
		@Override
		public void onSubscribe(Disposable d) {

		}

		@Override
		public void onNext(String serialNum) {
			if (! TextUtils.isEmpty (serialNum)) {
				Datas_load datasLoad = MyApp.getInstance ().getDatas_load ();
				if (datasLoad != null) {

//					Toast.makeText (CaptureActivity.this, "成功激活商家收款码", Toast.LENGTH_SHORT).show ();
//				Intent sk = new Intent (CaptureActivity.this, MyShoukuanActivity.class);
					Intent sk = new Intent (CaptureActivity.this, ChannelActivateActivity.class);
					sk.putExtra ("serialNum", serialNum);
					sk.putExtra ("userId", Integer.parseInt (datasLoad.getId ()));
					startActivity (sk);
					finish ();
				}

			}
		}

		@Override
		public void onError(Throwable e) {
			Toast.makeText (CaptureActivity.this, e.getMessage (), Toast.LENGTH_SHORT).show ();
		}

		@Override
		public void onComplete() {

		}
	};

}